# -*- coding:utf-8 -*-
# author: lkz
# date: 2016/11/23 10:27

import time
import socket
import os

from multiprocessing import Process


class PacketReceiver(Process):
    def __init__(self, packet_queue, ip_list, socket_buf_size):
        self.__packet_queue = packet_queue
        self.__ip_hash = dict([(ip, True) for ip in ip_list])
        self.__socket_buf_size = socket_buf_size
        self.__raw_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
        Process.__init__(self)

        self.running = True

    def run(self):
        while self.running:
            try:
                data, src = self.__raw_socket.recvfrom(self.__socket_buf_size)

                # 注意: 这里有一个大bug, 当别的程序在ping相同的ip时, 这里会把别的程序的ip也放进队列
                if src[0] not in self.__ip_hash:
                    continue

                self.__packet_queue.put((src[0], time.time(), data))
            except Exception as e:
                break

    def stop(self):
        self.__raw_socket.close()
        self.running = False
        os.kill(self.pid, 9)
